package net.sudot.chess.business.dao;

import net.sudot.chess.business.dto.RankDTO;
import net.sudot.chess.business.model.BaseEntity;
import net.sudot.chess.business.model.OrderGame;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.time.Instant;
import java.util.List;

/**
 * 排行榜
 *
 * @author tangjialin on 2018-05-07.
 */
@Repository
public class RankDao extends BaseDao<BaseEntity> {

    /**
     * 获取排行榜信息
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return 返回排行榜信息
     */
    public List<RankDTO> findList(Instant start, Instant end) {
        String ql = "SELECT new net.sudot.chess.business.dto.RankDTO(customer.id, customer.nickname, customer.head, COUNT(orderGame.id))" +
                " FROM Customer customer" +
                " INNER JOIN OrderGame orderGame ON orderGame.userId = customer.id AND orderGame.status = :status" +
                " WHERE orderGame.completeDate >= :start AND orderGame.completeDate < :end" +
                " GROUP BY customer.id" +
                " ORDER BY COUNT(orderGame.id) DESC, customer.createdDate ASC";
        TypedQuery<RankDTO> query = entityManager.createQuery(ql, RankDTO.class);
        query.setParameter("status", OrderGame.Status.COMPLETED);
        query.setParameter("start", start);
        query.setParameter("end", end);
        query.setMaxResults(10);
        return query.getResultList();
    }

    /**
     * 获取排行榜信息
     *
     * @param start   开始时间
     * @param end     结束时间
     * @param userIds 用户主键
     * @return 返回排行榜信息
     */
    public List<RankDTO> findList(Instant start, Instant end, List<Long> userIds) {
        String ql = "SELECT new net.sudot.chess.business.dto.RankDTO(customer.id, customer.nickname, customer.head, COUNT(orderGame.id))" +
                " FROM Customer customer" +
                " INNER JOIN OrderGame orderGame ON orderGame.userId = customer.id AND orderGame.status = :status" +
                " WHERE orderGame.completeDate >= :start AND orderGame.completeDate < :end" +
                " AND customer.id IN :userIds" +
                " GROUP BY customer.id";
        TypedQuery<RankDTO> query = entityManager.createQuery(ql, RankDTO.class);
        query.setParameter("status", OrderGame.Status.COMPLETED);
        query.setParameter("start", start);
        query.setParameter("end", end);
        query.setParameter("userIds", userIds);
        query.setMaxResults(10);
        return query.getResultList();
    }

}
